const URL = require('./server.config.js')
const app = getApp();

/**
 * @method
 * 小程序请求封装
 * 
 * @parmas {Object} url  接口地址
 * @parmas {Object}  data 接口参数
 * @parmas {Function} success 接口成功回调函数
 * @parmas {Function} callFail 接口失败回调函数
 * @parmas {Object} pageobj  页面对象this
 * @parmas {Boolean} isHeader 是否有请求头
 * @parmas {Boolean} cType 请求内容类型
 */
function api(url, data, success, callFail, pageObj, isPost, isHeader, cType) {
   let header = {},
      requestNum = 0;
   request();

   function request() {
      if (isHeader) {
         header = {
            'content-type': `${cType ? 'application/x-www-form-urlencoded' : 'application/json'}`,
            Authorization: app.data.loginInfo.token ? 'Bearer ' + app.data.loginInfo.token : 'Bearer ' + wx.getStorageSync('loginInfo').token,
            Accept: app.data.app_version
         }
      } else {
         header = {
            'content-type': `${cType ? 'application/x-www-form-urlencoded' : 'application/json'}`,
            Accept: app.data.app_version
         }
      }
      console.log('全局请求参数');
      console.log(url);
      console.log(data);
      console.log(header);
      wx.request({
         url: url,
         data: data,
         method: `${isPost ? 'POST' : 'GET'}`,
         header: header,
         success: function(res) {
            if (res.statusCode == 201 || res.statusCode == 200) {
               success(res);
            } else {
               if (res.statusCode == 412 || res.statusCode == 500 || res.status_code == 412) {
                  refreshServerToken((state) => {
                     if (state == '0' && requestNum < 3) {
                        request();
                        requestNum++;
                     }
                  });
                  return;
               }
               if (res.statusCode == 204 || res.statusCode == 422 || res.statusCode == 401 || res.statusCode == 412) return;
               var error_msg = 'error:接口请求错误';
               if (res.data.message != 'null' || res.data.message != '') {
                  error_msg = res.data.message;
               }
               wx.showModal({
                  title: '提示',
                  content: error_msg,
                  showCancel: false
               })
               wx.hideLoading();
            }
         },
         fail: function(error) {
            console.log('请求失败')
            console.log(error)
            wx.showModal({
               title: '',
               content: error.errMsg,
               showCancel: false
            })
         }
      });
   }
}


function loginRefreshServerToken(callback) {
   wx.login({
      success: function(res) {
         console.log(res)
         app.data['code'] = res.code;
         console.log('登陆成功')
         wx.request({
            url: URL.url_user_login,
            data: {
               code: res.code
            },
            method: 'POST',
            header: {
               Accept: app.data.app_version,
               miniName: app.data.miniName
            },
            success(res) {
               console.log('重新登录返回')
               console.log(res)
               var datas = res.data.data.authorization.data;
               app.data.loginInfo = datas;
               wx.setStorageSync('loginInfo', datas)
               callback('0');
            },
            fail(res) {
               // callback('1');
               if (res.data.message != 'null' || res.data.message != '') {
                  error_msg = res.data.message
               }
               wx.showModal({
                  title: '提示',
                  content: error_msg,
                  showCancel: false
               })
            },
         })
      },
      fail: function(res) {
         console.log('登录失败')
         console.log(res)
         wx.showToast({
            title: 'wx.login:登录失败',
            icon: 'none',
            duration: 3000,
            mask: true,
         })
         // callback('2');
      }
   })
}

function refreshServerToken(callback) {
   wx.request({
      url: URL.url_token_refresh,
      method: 'POST',
      header: {
         Authorization: app.data.loginInfo.token ? 'Bearer ' + app.data.loginInfo.token : 'Bearer ' + wx.getStorageSync('loginInfo').token,
         Accept: app.data.app_version,
         miniName: app.data.miniName
      },
      success(res) {
         console.log('刷新token返回')
         console.log(res)
         var datas = res.data.data.authorization.data;
         app.data.loginInfo = datas;
         wx.setStorageSync('loginInfo', datas)
         callback('0');
      },
      fail(res) {
         // callback('1');
         if (res.data.message != 'null' || res.data.message != '') {
            error_msg = res.data.message
         }
         wx.showModal({
            title: '提示',
            content: error_msg,
            showCancel: false
         })
      },
   })
}

/**
 * method
 * 图片上传
 * 
 * @parsm {String} url 上传接口
 * @parsm {Object} data 上传数据
 * @parsm {Function} success 上传成功回调
 * @parsm {Function} callFail 上传失败回调
 * @parsm {Obejct} pageobj 页面对象
 */
function upload(url, data, success, callFail, pageobj) {
   let uploadTask = wx.uploadFile({
      url: url,
      filePath: data.filePath,
      name: data.name,
      formData: data.formData,
      header: {
         Accept: app.data.app_version,
         miniName: app.data.appid
      },
      success: (res) => {
         var data = res.data
         console.log('upload:', res, res.data)
         let fileData = JSON.parse(res.data).files;
         if (res.statusCode == 200) {
            success(res);
            // wx.showToast({
            //     title: '上传成功！',
            //     icon: 'success',
            //     duration: 500
            // })
         } else {
            var error_msg = 'error:接口请求错误';
            if (res.data.message != 'null' || res.data.message != '') {
               error_msg = res.data.message
            }
            wx.showModal({
               title: '提示',
               content: error_msg,
               showCancel: false
            })
         }
      },
      fail: res => {
         console.log(res)
         wx.showToast({
            title: '上传失败',
            icon: 'loading',
            duration: 1000
         })
      }
   })
   uploadTask.onProgressUpdate((res) => {
      // console.log('上传进度', res.progress)
      // console.log('已经上传的数据长度', res.totalBytesSent)
      // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
      pageobj.setData({
         uploading: 1,
         uploadProgress: res.progress
      })
   })
}

function submitRequstErrorLog(error) {
   wx.request({
      url: URL.URL_LOG_SAVE,
      data: {
         wx_version: app.data.wx_version,
         sdk_version: app.data.sdk_version,
         app_version: app.data.app_version,
         system: app.data.system,
         project: app.data.project,
         mid: app.data.mid,
         error: error
      },
      method: 'POST',
      success(res) {
         console.log('提交错误日志success返回')
         console.log(res)
      },
      fail(res) {
         console.log('提交错误日志fail返回')
         console.log(res)
      },
   })
}

module.exports = {
   api,
   upload
}